package com.lehoon.tomato.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lehoon.tomato.config.JwtConfig;
import com.lehoon.tomato.mapper.UserMapper;
import com.lehoon.tomato.model.User;
import com.lehoon.tomato.model.common.Result;
import com.lehoon.tomato.model.user.UserBase;
import com.lehoon.tomato.model.vo.LoginVo;
import com.lehoon.tomato.model.wechat.WxAuthCodeMessage;
import com.lehoon.tomato.service.LoginService;
import com.lehoon.tomato.service.WeChatService;
import com.lehoon.tomato.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private WeChatService weChatService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtConfig jwtConfig ;

    @Override
    public LoginVo doWxLogin(String code) {
        LoginVo vo = new LoginVo();
        WxAuthCodeMessage message = weChatService.checkCode2Seesion(code);
        if (message==null|| StringUtils.isEmpty(message.getOpenid())||StringUtils.isEmpty(message.getUnionid())){
            throw new RuntimeException("未获取到用户信息");
        }

        //根据unionid 查询 数据库 有则登录 没有则注册
        User user = userMapper.getUserByUnionId(message.getUnionid());
        if (user==null) {
            vo.setIfExits(false);
            //插入基础信息
            user = new User();
            user.setXcxOpenid(message.getOpenid());
            user.setUnionid(message.getUnionid());
            user.setPlatform(4);
            user.setCreateTime(System.currentTimeMillis());
            userMapper.insertSimpleUser(user);
        }else {
            vo.setIfExits(true);
            //更新用户小程序openId字段
            if (StringUtils.isEmpty(user.getXcxOpenid())){
                user.setXcxOpenid(message.getOpenid());
                userMapper.updateUserInfo(user);
            }
        }
        UserBase userBase = new UserBase();
        userBase.setId(user.getId());
        userBase.setXcxOpenid(message.getOpenid());
        userBase.setUnionid(message.getUnionid());
        vo.setToken(jwtConfig.getToken(JSONObject.toJSONString(userBase)));
        return vo;
    }
}
